package com.yihen.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.yihen.dto.UserDTO;
import com.yihen.vo.UserVO;
import com.yihen.pojo.User;
import com.yihen.service.impl.IUserService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.yihen.util.Constants.LOGIN_USER_KEY;
import static com.yihen.util.Constants.LOGIN_USER_TTL;


public class RefreshTokenInterceptor implements HandlerInterceptor  {

    private StringRedisTemplate stringRedisTemplate;

    private IUserService userService;

    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate, IUserService userService) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.userService = userService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //  1. 获取请求头中的token
        String token = request.getHeader("authorization");
        if (StrUtil.isBlank(token)) {
            return true;
        }
        //  2. 基于TOKEN 获取redis中的用户
        Map<Object, Object> userMapper = stringRedisTemplate.opsForHash().entries(LOGIN_USER_KEY + token);
        // 3. 判断用户是否存在
        if (userMapper.isEmpty()) {
            return true;
        }
        // 5. 获取userId
        Long id= BeanUtil.fillBeanWithMap(userMapper, new UserDTO(), false).getUserId();
        String s = stringRedisTemplate.opsForValue().get("user:" + id.toString());
        String uservo = stringRedisTemplate.opsForValue().get("user_root:" + id.toString());

        UserVO userVO;
        UserDTO userDTO;
        if (s!=null){
            userDTO = JSONUtil.toBean(s, UserDTO.class);
            userVO = JSONUtil.toBean(uservo, UserVO.class);
            UserHolder.saveUser(userVO);
        }else {
            User user_ = userService.getById(id);
            userVO = BeanUtil.copyProperties(user_, UserVO.class);
            userDTO = BeanUtil.copyProperties(user_, UserDTO.class);
            stringRedisTemplate.opsForValue().setIfAbsent("user:" + id.toString(), JSONUtil.toJsonStr(userDTO));
            // 6. 存在，保存用户信息到ThreadLocal
            UserHolder.saveUser(userVO);
        }

        // 5.1


        // 7. 刷新token有效期
        stringRedisTemplate.expire(LOGIN_USER_KEY + token, LOGIN_USER_TTL, TimeUnit.MINUTES);
        // 刷新基本信息有效期
        stringRedisTemplate.expire("user:"+id.toString(), LOGIN_USER_TTL, TimeUnit.MINUTES);
        stringRedisTemplate.expire("user_root:"+id.toString(), LOGIN_USER_TTL, TimeUnit.MINUTES);
        // 6. 放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
       // 移除用户
        UserHolder.removeUser();
    }
}
